package com.crown.spring;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;

import com.crown.spring.annotation.LResource;
import com.crown.spring.annotation.Lservice;
import com.crown.spring.test.UserService;
import com.crown.spring.utils.ClassUtil;

public class LIocAnnotationApplicationContext {
	
	private String packagePath;
	public  static ConcurrentHashMap<String, Object>  container = new ConcurrentHashMap<String, Object>();;
	
	
	public LIocAnnotationApplicationContext(String packagePath) {
		// TODO Auto-generated constructor stub\
		this.packagePath = packagePath;
	}
	
	
	public Object initBenas(String beanId) throws Exception{
		//获得当前包下所有的类
		List<Class<?>> classes = getSacnedBaens();
		//初始化所有的bean
		container = initBean(classes);
		//判断是否存在当前bean对象
		Object object = container.get(beanId);
		if (object==null) {
			throw new  Exception("找不到Bean对象");
		}
		asSign(object);
		//使用反射机制惊醒初始化
		return object;
	}
	
	
	public List<Class<?>> getSacnedBaens() throws Exception {
		if (StringUtils.isEmpty(packagePath)) {
			 throw  new Exception("包的路径不能为空"); 
		}
		List<Class<?>> classes = ClassUtil.getClasses(packagePath);
		List<Class<?>> beans = new ArrayList<>();
		for (Class<?> object : classes) {
			Lservice annotation = object.getAnnotation(Lservice.class);
			if (annotation!=null) {
				beans.add(object);
				continue;
			}
		}
		return beans;
	}
	
	public ConcurrentHashMap<String, Object> initBean(List<Class<?>> classes) throws Exception{
		ConcurrentHashMap<String, Object> container = new ConcurrentHashMap<String, Object>();
		for (Class<?> class1 : classes) {
			String className = getDefaultBeanName(class1.getSimpleName());
			container.put(className, class1.newInstance());
		}
		return container;
	}
	
	private  String getDefaultBeanName(String  name) {
		// TODO Auto-generated method stub
		if (Character.isLowerCase(name.charAt(0))) {
			return name;
		}
		return  new StringBuilder().append(Character.toLowerCase(name.charAt(0))).append(name.substring(1)).toString();
	}
	
	
	
	//获得类的所有的属性 
	//检查是否有@Resource注解
	//有的话通过反射实例化
	public  void asSign(Object object) throws Exception {
		List<Field> fields = Arrays.asList(object.getClass().getDeclaredFields());
		for (Field field : fields) {
			boolean isContain = isContain(field);
			if (isContain) {
				String name = field.getName();
				Object bean = container.get(name);
				if ( bean != null) {
					field.setAccessible(true);
					field.set(object,bean);
				}
				continue;
			}
		}
		
	}
	

	
	public boolean isContain(Field field) {
		Annotation annotation = field.getAnnotation(LResource.class);
		if (annotation!=null) {
			return true;
		}
		return false;
	}
	
	
	

}
